<?php
namespace App\Job\Prize;

use App\Query\UserQuery;
use App\Repository\LevelRepository;
use App\Repository\UserRepository;

// 感恩奖
class Thank
{
    public $money;
    
    public $all;
    
    public $users;
    
    public function __construct($money, $all)
    {
        $this->all = $all;
        $this->money = $money;
    }
    
    // 运行
    public function run($content)
    {
        // 查找今日有动态的用户组
        foreach(UserQuery::in(UserQuery::moneyTime(UserQuery::model()), $this->all)->get() as $user)
        {
            $this->users[$user->id] = $user;
        }
        
        // 发放一级奖励
        $this->prize('thank', $content);
    
        // 发放二级奖励
        $this->prize('thankTwo', $content);
    }
    
    // 发放奖励
    public function prize($func, $content)
    {
        // 查找关系链
        while($this->all)
        {
            // 用户ID
            $id = array_pop($this->all);
            
            // 判断是否有动态
            if($user = $this->users[$id] ?? null)
            {
                // 用户
                $user = UserRepository::make($user);
                
                // 用户等级
                $level = LevelRepository::make($user->level);
                
                // 算出奖，如果没有，说明不符合，继续往上找
                if($money = (float) $level->$func($this->money))
                {
                    // 发放
                    return $user->orderMoneyRemain('thank', $money, $content);
                }
            }
        }
    }
}